<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="form.riskName !== null" :span="12">
          <el-form-item :label="$t('风险名称')" prop="riskName">
            <el-input v-model="form.riskName" maxlength="125" show-word-limit :placeholder="$t('风险名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('风险等级')" prop="riskLevel">
            <el-select v-model="form.riskLevel" :placeholder="$t('风险等级')">
              <el-option
                v-for="dict in levelOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('风险类型')" prop="riskType">
            <el-select v-model="form.riskType" :placeholder="$t('风险类型')">
              <el-option
                v-for="dict in riskTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生概率')" prop="probability">
            <el-select v-model="form.probability" :placeholder="$t('发生概率')">
              <el-option
                v-for="dict in levelOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('损失程度')" prop="loss">
            <el-select v-model="form.loss" :placeholder="$t('损失程度')">
              <el-option
                v-for="dict in levelOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('风险状态')" prop="riskState">
            <el-select v-model="form.riskState" :placeholder="$t('风险状态')" @change="riskStateChange">
              <el-option
                v-for="dict in riskStateOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isShowRiskTime" :span="12">
          <el-form-item :label="$t('发生时间')" prop="riskTime">
            <DatePicker v-model="form.riskTime" :placeholder="$t('发生时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒人')" prop="remindUser">
            <UserSelect
              v-model="form.remindUser"
              :multiple="true"
              fund-invest
              :placeholder="$t('提醒人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
            <el-radio-group v-model="form.reminderFrequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderFrequency === 'TIMER'" :span="12">
          <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
            <el-date-picker
              v-model="form.remindTime"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :placeholder="$t('定时提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-else :span="24">
          <el-form-item :label="$t('频率提醒表达式')" prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('风险敞口金额') + $t('金额单位')" prop="riskExposure">
            <Money
              v-model="form.riskExposure"
              unit="w"
              placeholder="风险敞口金额"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('损失金额') + $t('金额单位')" prop="riskLoss">
            <Money
              v-model="form.riskLoss"
              unit="w"
              placeholder="损失金额"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowCloseCause" :span="24">
          <el-form-item :label="$t('关闭原因')" prop="closeCause">
            <el-input v-model="form.closeCause" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('关闭原因')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('风险事项描述')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('风险事项描述')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('风险控制情况')" prop="remark">
            <el-input v-model="form.riskControl" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('风险控制情况')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="area-header" style="margin-top: 10px">
            <span class="area-header-title">{{ $t("下一步风险处置安排") }}</span>
          </div>
          <el-table
            :data="form.dealRiskPlanList"
            style="width: 100%"
            class="nowrapTable formTable"
            border
          >
            <el-table-column label="措施内容" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("措施内容") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'dealRiskPlanList.' + scope.$index + '.measureContent'"
                  :rules="dealRiskPlanListRules.measureContent"
                >
                  <el-input v-model="scope.row.measureContent" :placeholder="$t('措施内容')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureTime" label="措施完成时间" align="center">
              <template slot="header" slot-scope="{}">
                <!-- <i style="color: #ff4949; margin-right: 4px">*</i> -->
                <span>{{ $t("措施完成时间") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item>
                  <el-date-picker
                    v-model="scope.row.measureTime"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('操作')"
              align="center"
              class-name="small-padding fixed-width"
              width="140"
            >
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="delDealRiskPlan(scope.$index, scope.row)"
                >{{ $t("删除") }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addDealRiskPlan"
            >{{ $t("添加") }}</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 重大风险应对 -->
      <el-row>
        <el-col :span="24">
          <div class="area-header" style="margin-top: 10px">
            <span class="area-header-title">{{ $t("重大风险应对") }}</span>
          </div>
          <el-table :data="form.dealRiskGreatReplyList" style="width: 100%" class="nowrapTable formTable" border>
            <el-table-column label="风险处置方案名称" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("风险处置方案名称") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealRiskGreatReplyList.' + scope.$index + '.riskPlanName'" :rules="dealRiskGreatReplyListRules.riskPlanName">
                  <el-input v-model="scope.row.riskPlanName" :placeholder="$t('风险处置方案名称')" show-word-limit maxlength="100" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureTime" label="风险事项描述" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t("风险事项描述") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealRiskGreatReplyList.' + scope.$index + '.eventDescription'">
                  <el-input v-model="scope.row.eventDescription" :placeholder="$t('风险事项描述')" show-word-limit maxlength="1000" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureTime" label="风险事项描述" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t("风险发生原因") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealRiskGreatReplyList.' + scope.$index + '.happenReason'">
                  <el-input v-model="scope.row.happenReason" :placeholder="$t('后续处理措施')" show-word-limit maxlength="1000" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureTime" label="风险事项描述" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t("后续处理措施") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealRiskGreatReplyList.' + scope.$index + '.treatmentMeasure'">
                  <el-input v-model="scope.row.treatmentMeasure" :placeholder="$t('后续处理措施')" show-word-limit maxlength="1000" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="140">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="delDealRiskGreatReply(scope.$index, scope.row)"
                >{{ $t("删除") }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addDealRiskGreatReply"
            >{{ $t("添加") }}</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 已采取的风险控制措施 -->
      <el-row>
        <el-col :span="24">
          <div class="area-header" style="margin-top: 10px">
            <span class="area-header-title">{{ $t("已采取的风险控制措施") }}</span>
          </div>
          <el-table
            :data="form.dealRiskAdoptedMeasureList"
            style="width: 100%"
            class="nowrapTable formTable"
            border
          >
            <el-table-column label="措施内容" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ $t("措施内容") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'dealRiskAdoptedMeasureList.' + scope.$index + '.measureContent'"
                  :rules="dealRiskAdoptedMeasureListRules.measureContent"
                >
                  <el-input v-model="scope.row.measureContent" :placeholder="$t('措施内容')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureTime" label="措施完成时间" align="center">
              <template slot="header" slot-scope="{}">
                <!-- <i style="color: #ff4949; margin-right: 4px">*</i> -->
                <span>{{ $t("措施完成时间") }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item>
                  <el-date-picker
                    v-model="scope.row.measureTime"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('操作')"
              align="center"
              class-name="small-padding fixed-width"
              width="140"
            >
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="delDealRiskAdoptedMeasure(scope.$index, scope.row)"
                >{{ $t("删除") }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addDealRiskAdoptedMeasure"
            >{{ $t("添加") }}</el-button>
          </div>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="deal:risk" data-type="deal_risk" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!btnHide" />
    </el-form>
    <div v-if="!btnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn v-if="outside" has-permi="deal:risk" />
    </div>
  </div>
</template>

<script>
    import { saveDealRisk, getDealRisk, delDealRiskPlan } from '@/api/deal/risk/dealRisk'
    import Cron from '@/components/Cron'
    import { delDealRiskGreatReply } from '@/api/deal/risk/riskGreatReply/dealRiskGreatReply'
    import { delDealRiskAdoptedMeasure } from '@/api/deal/risk/riskAdoptedMeasure/dealRiskAdoptedMeasure'
    export default {
      components: {
        Cron
      },
      props: {
        dealId: {
          type: String,
          default: undefined
        },
         outside: {
          type: Boolean,
          default: true
        }
      },
        data() {
            return {
                // 是否隐藏保存等按钮
                btnHide: false,
                // level字典
                levelOptions: [], // 风险类型、发生概率、损失程度 字典level字典
                riskTypeOptions: [], // 风险类型 字典risk_type
                riskStateOptions: [], // 风险状态 字典risk_status
                form: {
                  fileList: [],
                  dealRiskPlanList: [],
                  dealRiskGreatReplyList: [],
                  dealRiskAdoptedMeasureList: []
                },
                // 遮罩层
                loading: false,
                // 表单校验
              rules: {
                riskName: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], riskLevel: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], riskType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], probability: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], loss: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], riskState: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], riskTime: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ] },
                // 是否显示风险时间
                isShowRiskTime: false,
                // 是否显示关闭原因
                isShowCloseCause: false,
                reminderFrequencyOptions: [],
                dealRiskPlanListRules: {
                    measureContent: [
                      { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ]
                },
                dealRiskGreatReplyListRules: {
                  riskPlanName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                dealRiskAdoptedMeasureListRules: {
                  measureContent: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                }
            }
        },
        created() {
            this.getDicts('level').then(response => {
                this.levelOptions = response.data
            })
            this.getDicts('risk_status').then(response => {
                this.riskStateOptions = response.data
            })
            this.getDicts('risk_type').then(response => {
                this.riskTypeOptions = response.data
            })
            this.getDicts('reminder_frequency').then(response => {
              this.reminderFrequencyOptions = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealRisk(data.id).then(response => {
                        this.form = response.data
                        this.riskStateChange(this.form.riskState)
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
                if (this.form.riskState !== null) {
                  this.riskStateChange(this.form.riskState)
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                dealId: this.$route.query.id || this.dealId,
                riskName: undefined,
                riskLevel: undefined,
                riskType: undefined,
                probability: undefined,
                loss: undefined,
                riskState: 'GZ',
                riskTime: undefined,
                fileList: [],
                remark: undefined,
                closeCause: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                remindUserId: [],
                remindTime: undefined,
                reminderFrequency: 'TIMER',
                status: 1
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveDealRisk(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                              this.loading = false
                            }
                        }).catch(() => {
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          riskStateChange(value) {
            if (value === 'FS') {
              this.isShowRiskTime = true
              this.isShowCloseCause = false
              this.form.closeCause = undefined
            } else if (value === 'GB') {
              this.isShowCloseCause = true
              this.isShowRiskTime = true
            } else {
              this.isShowCloseCause = false
              this.isShowRiskTime = false
              this.form.closeCause = undefined
              this.form.riskTime = undefined
            }
          },
          addDealRiskPlan() {
              const row = {
                id: undefined,
                measureContent: undefined,
                measureTime: undefined
              }
              if (!(this.form.dealRiskPlanList instanceof Array)) {
                this.$set(this.form, 'dealRiskPlanList', [])
              }
              this.$nextTick(() => {
                this.form.dealRiskPlanList.push(row)
              })
          },
          delDealRiskPlan(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(() => {
                    // 调用接口
                     delDealRiskPlan(id)
                    this.form.dealRiskPlanList.splice(index, 1)
                    return this.msgSuccess(this.$t('删除成功'))
                  })
                  .catch(function() {})
              } else {
                this.form.dealRiskPlanList.splice(index, 1)
              }
          },
          // 添加重大风险应对
          addDealRiskGreatReply() {
              const row = {
                id: undefined,
                riskId: undefined,
                riskPlanName: undefined,
                eventDescription: undefined,
                happenReason: undefined,
                treatmentMeasure: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined
              }
              if (!(this.form.dealRiskGreatReplyList instanceof Array)) {
                this.$set(this.form, 'dealRiskGreatReplyList', [])
              }
              this.$nextTick(() => {
                this.form.dealRiskGreatReplyList.push(row)
              })
          },
          // 删除重大风险应对
          delDealRiskGreatReply(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(() => {
                    // 调用接口
                    delDealRiskGreatReply(id)
                    this.form.dealRiskGreatReplyList.splice(index, 1)
                    return this.msgSuccess(this.$t('删除成功'))
                  })
                  .catch(function() {})
              } else {
                this.form.dealRiskGreatReplyList.splice(index, 1)
              }
          },
          // 添加已采取的风险控制措施
          addDealRiskAdoptedMeasure() {
              const row = {
                id: undefined,
                riskId: undefined,
                riskPlanName: undefined,
                eventDescription: undefined,
                happenReason: undefined,
                treatmentMeasure: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined
              }
              if (!(this.form.dealRiskAdoptedMeasureList instanceof Array)) {
                this.$set(this.form, 'dealRiskAdoptedMeasureList', [])
              }
              this.$nextTick(() => {
                this.form.dealRiskAdoptedMeasureList.push(row)
              })
          },
          // 删除已采取的风险控制措施
          delDealRiskAdoptedMeasure(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(() => {
                    // 调用接口
                    delDealRiskAdoptedMeasure(id)
                    this.form.dealRiskAdoptedMeasureList.splice(index, 1)
                    return this.msgSuccess(this.$t('删除成功'))
                  })
                  .catch(function() {})
              } else {
                this.form.dealRiskAdoptedMeasureList.splice(index, 1)
              }
          }
        }

    }
</script>
